<template>
  <div class="app-container org">
    <el-card style="width: 100%">
      <p class="pinformation">搜索条件</p>
      <el-form label-width="90" ref="queryRef" :model="queryParams">
        <el-row>
          <el-col :span="4">
            <el-form-item label="检测类别组：" prop="jclbGroupName">
              <el-input maxlength="100" clearable placeholder="请输入检测类别组" v-model.trim="queryParams.jclbGroupName"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="检测项目：" prop="jcxmName">
              <el-input maxlength="100" clearable placeholder="请输入检测项目" v-model.trim="queryParams.jcxmName"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="方法编号：" prop="methodCode">
              <el-input maxlength="100" clearable placeholder="请输入方法编号" v-model.trim="queryParams.methodCode"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="方法名称：" prop="methodName">
              <el-input maxlength="100" clearable placeholder="请输入方法名称" v-model.trim="queryParams.methodName"
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-row justify="center">
              <el-radio v-model="queryParams.isLike" label="0">模糊搜索</el-radio>
              <el-radio v-model="queryParams.isLike" label="1">精准搜索</el-radio>
            </el-row>
          </el-col>
          <el-col :span="4">
            <el-button style="margin-left: 15px;" type="success" @click="handleQuery">搜索</el-button>
            <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="计量认证是否通过：" label-width="130" prop="isAuth">
              <el-select v-model="queryParams.isAuth">
                <el-option v-for="item in isPassThroughList" :key="item.value" :value="item.value"
                  :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="国家实验室认证是否通过：" label-width="170" prop="isAgree">
              <el-select v-model="queryParams.isAgree">
                <el-option v-for="item in isPassThroughList" :key="item.value" :value="item.value"
                  :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="本机构是否使用：" label-width="120" prop="isUse">
              <el-select v-model="queryParams.isUse">
                <el-option v-for="item in isUseList" :key="item.value" :value="item.value"
                  :label="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <p class="pinformation" style="margin-top: 8px">数据列表</p>
        <p class="totalStyle" style="margin-top: 6px">共 {{ total }} 条数据</p>
        <p class="totalStyle" style="margin-top: 6px">检测项目总数：{{ countForm.jcxmCount }}</p>
        <p class="totalStyle" style="margin-top: 6px">检测方法总数：{{ countForm.methodCount }}</p>
        <el-row style=" margin-left: 20px">
          <el-button link type="success" :disabled="!selectionList.length"
            @click="isChange(false, 'isUse', 'isAuth', 'isAgree')">本机构批量使用</el-button>
          <el-button link type="success" :disabled="!selectionList.length"
            @click="isChange(false, 'isAuth', 'isUse', 'isAgree')">计量认证批量通过</el-button>
          <el-button link type="success" :disabled="!selectionList.length"
            @click="isChange(false, 'isAgree', 'isUse', 'isAuth')">国家实验室认可批量通过</el-button>
          <el-button link type="success" icon="Download" @click="handleExport">导出资质表</el-button>
          <el-button link type="success" icon="Upload" @click="handleImport">导入数据</el-button>
          <el-button link type="success" icon="Refresh" @click="handleSynchronous" :loading="logining">同步数据</el-button>
        </el-row>
      </el-row>
      <el-table border ref="mainTableRef" class="business" v-loading="loading" :data="dataTable"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" align="center" width="55" />
        <el-table-column label="检测类别组" align="center" prop="jclbGroupName" />
        <el-table-column label="检测类别" align="center" prop="jclbNames" />
        <el-table-column label="检测项目" align="center" prop="jcxmName" width="150">
          <template #default="scope">
            <span v-html="proxy.getSupAndSub(scope.row.jcxmName)"></span>
          </template>
        </el-table-column>
        <el-table-column label="方法编号" align="center" prop="methodCode" />
        <el-table-column label="方法名称" align="center"  width="550" >
          <template #default="scope">
            <span v-html="proxy.getSupAndSub(scope.row.methodName)"></span>
          </template>
        </el-table-column>
        <el-table-column label="本机构是否使用" align="center" prop="isUse" width="160">
          <template #default="scope">
            <el-checkbox v-model="scope.row.isUse" label="使用" size="large" @change="isChange(scope.row, 'isUse')" />
          </template>
        </el-table-column>
        <el-table-column label="计量认证是否通过" align="center" prop="isAuth" width="160">
          <template #default="scope">
            <el-checkbox v-model="scope.row.isAuth" label="通过" size="large" @change="isChange(scope.row, 'isAuth')" />
          </template>
        </el-table-column>
        <el-table-column label="国家实验室认证是否通过" align="center" prop="isAgree" width="200">
          <template #default="scope">
            <el-checkbox v-model="scope.row.isAgree" label="通过" size="large" @change="isChange(scope.row, 'isAgree')" />
          </template>
        </el-table-column>
        <el-table-column label="是否现场检测" align="center" prop="isWith" width="90">
          <template #default="scope">
            <el-checkbox v-model="scope.row.isWith" label="是" size="large" @change="isChangeWith(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 数据导入对话框 -->
    <el-dialog :class="'el-dialog-theme3'" :title="upload.title" v-model="upload.open" width="400px"
      append-to-body draggable :close-on-click-modal="false">
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-error="handleUploadError" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="success" :underline="false" style="font-size: 12px; vertical-align: baseline"
              @click="handleExport">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="submitFileForm">确 定</el-button>
          <el-button type="danger" @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="JcffConfig">
import {
  jcffList,
  jcffPut,
  jcffCount,
  postSynchronous,
  getQualifyStatus,
} from "@/api/store/jcffConfig";
import { ElMessageBox } from "element-plus";
import { onMounted } from "vue";
import { getToken } from "@/utils/auth";

const { proxy } = getCurrentInstance();
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  isAuth: -1,
  isAgree: -1,
  isUse: -1,
  isLike: "0",
});
const mainQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  isAuth: -1,
  isAgree: -1,
  isUse: -1,
  isLike: "0",
})
const loading = ref(false);
const logining = ref(false);
const dataTable = ref([]);
const total = ref(0);
const selectionList = ref([]);

const isPassThroughList = ref([
  { value: -1, label: "全部" },
  { value: 0, label: "未通过" },
  { value: 1, label: "通过" },
]);
const isUseList = ref([
  { value: -1, label: "全部" },
  { value: 0, label: "未使用" },
  { value: 1, label: "使用" },
]);
// -------------------导入模板逻辑-------------------
/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的数据
  updateSupport: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/lims/store/qualify/importData",
});
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

const countForm = ref({});

function getList() {
  return new Promise((resolve, reject) => {
    loading.value = true;
    jcffList(queryParams.value).then((res) => {
      dataTable.value = res.rows;
      total.value = res.total;
      mainQueryParams.value = JSON.parse(JSON.stringify(queryParams.value))
      dataTable.value.forEach((item) => {
        item.isUse ? (item.isUse = true) : (item.isUse = false);
        item.isAgree ? (item.isAgree = true) : (item.isAgree = false);
        item.isAuth ? (item.isAuth = true) : (item.isAuth = false);
        item.isWith ? (item.isWith = true) : (item.isWith = false);
      });
      loading.value = false;
      resolve();
    });
  });
}

function getCount() {
  jcffCount().then((res) => {
    countForm.value = res.data;
  });
}

getCount();

function isChangeWith(row){
  let temp = {jclbGroupId: row.jclbGroupId,jcxmId: row.jcxmId,methodId: row.methodId};
  temp.isWith = row.isWith ? 1 : 0;
  jcffPut([temp]).then(async (res) => {
    proxy.$modal.msgSuccess("保存成功");
  });
}
function isChange(row, name, delName1, delName2) {
  let temp =
    JSON.parse(JSON.stringify(row)) ||
    JSON.parse(JSON.stringify(selectionList.value));
  if (row) {
    if (name != "isUse") {
      if (!row.isUse) {
        if (row.isAgree || row.isAuth) {
          row.isUse = true;
        }
      }
    }
    if (row.isAuth) {
      temp.isAuth = 1;
    } else {
      temp.isAuth = 0;
    }
    if (row.isAgree) {
      temp.isAgree = 1;
    } else {
      temp.isAgree = 0;
    }
    if (row.isUse) {
      temp.isUse = 1;
    } else {
      temp.isUse = 0;
    }
    temp = [temp];
  } else {
    proxy.$modal.loading("正在处理中，请稍候...");
    temp.forEach((item) => {
      eval("item." + name + "=1");
      eval("delete item." + delName1);
      eval("delete item." + delName2);
      if (name != "isUse") {
        if (!item.isUse) {
          if (item.isAgree || item.isAuth) {
            item.isUse = 1;
          }
        }
      }
    });
  }
  let temp1 = [];
  temp.forEach((item) => {
    temp1.push({
      isUse: item.isUse,
      isAgree: item.isAgree,
      isAuth: item.isAuth,
      methodId: item.methodId,
      jcxmId: item.jcxmId,
      jclbGroupId: item.jclbGroupId,
    });
  });
  jcffPut(temp1).then(async (res) => {
    proxy.$modal.msgSuccess("保存成功");
    getCount();
    if (!row) {
      proxy.$modal.closeLoading();
      getList().then((res) => {
        temp1.forEach((item) => {
          dataTable.value.forEach((item1) => {
            if (item.id == item1.id) {
              proxy.$refs["mainTableRef"].toggleRowSelection(item1, true);
            }
          });
        });
      });
    }
  }).catch(res => {
    if (!row) proxy.$modal.closeLoading();
  })
}

function handleSelectionChange(selection) {
  selectionList.value = JSON.parse(JSON.stringify(selection));
}

getList();

watch(
  () => total.value,
  () => {
    if (total.value) {
      heightParams.value = [{ tableName: "main", bottomHeight: 73 }];
    } else {
      heightParams.value = [{ tableName: "main", bottomHeight: 21 }];
    }
    getTableHeight();
  }
);

const heightParams = ref([{ tableName: "main", bottomHeight: 21 }]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}

onMounted(() => {
  nextTick(function () {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})

onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});

function handleSynchronous() {
  proxy.$modal
    .confirm("确认要同步数据吗？")
    .then(() => {
      postSynchronous();
      logining.value = true;
      let timer = setInterval(() => {
        getQualifyStatus()
          .then((res) => {
            if (res.data == 2) {
              clearInterval(timer);
              logining.value = false;
              getList();
              ElMessageBox.alert("同步成功", "提示", {
                type: "success",
              });
            }
          })
          .catch(() => {
            clearInterval(timer);
            logining.value = false;
            ElMessageBox.alert("同步失败", "提示", {
              type: "error",
            });
          });
      }, 5000);
    })
    .catch(() => { });
}

// function getRowKey(row) {
//   return row.id;
// }

/** 导入按钮操作 */
function handleImport() {
  upload.title = "资质导入";
  upload.open = true;
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
    response.msg +
    "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

// 上传失败
function handleUploadError(err) {
  upload.isUploading = false;
  proxy.$modal.msgError("导入数据失败，原因：" + err.message);
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "lims/store/qualify/export",
    {
      ...mainQueryParams.value,
    },
    `资质配置表.xlsx`
  );
}
</script>

<style></style>
